/* ======================================================= */
/**
 * File : IsiHikingProvider.java Date : Jan 25, 2010 at 9:32:21 PM
 */
/* ======================================================= */
package fr.isima.data;

import java.io.File;
import java.util.Date;

import fr.isima.model.Track;
import fr.isima.tools.FileUtils;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/* ======================================================= */
/**
 * @author daniel
 */
/* ======================================================= */
public class IsiHikingProvider extends ContentProvider
{

    /** Debug Tag */
    private static final String     TAG                       = "IsiHikingProvider";

    public static final String      AUTHORITY                 = "fr.isima.data.isihikingprovider";

    public static final Uri         CONTENT_URI               = Uri
                                                                      .parse("content://"
                                                                              + AUTHORITY
                                                                              + "/tracks");
    /** Differentiate the URI requests */
    private static final int        PROVIDE_TRACKS            = 1;
    private static final int        PROVIDE_TRACK_ID          = 2;

    /* ======================================================= */
    /* Track */
    /* ======================================================= */
    /** Track table name */
    public static final String      TRACK_TABLE               = "track";

    /** Track table schema */
    public static final String      TRACK_ID                  = "track_id";
    public static final int         COLUMN_TRACK_ID           = 0;

    public static final String      TRACK_NAME                = "track_name";
    public static final int         COLUMN_TRACK_NAME         = 1;

    public static final String      TRACK_PATH                = "track_path";
    public static final int         COLUMN_TRACK_PATH         = 2;

    public static final String      TRACK_DATE                = "track_date";
    public static final int         COLUMN_TRACK_DATE         = 3;

    public static final String      TRACK_FREQ_REFRESH        = "track_freq_refresh";
    public static final int         COLUMN_TRACK_FREQ_REFRESH = 4;

    public static final String      TRACK_DIST_REFRESH        = "track_dist_refresh";
    public static final int         COLUMN_TRACK_DIST_REFRESH = 5;

    private static final UriMatcher uriMatcher;

    static
    {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        uriMatcher.addURI(AUTHORITY, "tracks", PROVIDE_TRACKS);

        uriMatcher.addURI(AUTHORITY, "tracks" + "/#", PROVIDE_TRACK_ID);
    }

    private IsiHikingOpenHelper     helper;
    private SQLiteDatabase          database;

    /* ======================================================= */
    /*
     * @see android.content.ContentProvider#delete(android.net.Uri,
     * java.lang.String, java.lang.String[])
     */
    /* ======================================================= */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs)
    {
        int count;

        switch (uriMatcher.match(uri))
        {
            case PROVIDE_TRACKS:

                /*
                 * Put "1" in where clause to remove all rows and get the count
                 * value
                 */

                selection = (!TextUtils.isEmpty(selection)) ? selection : "1";          
                count = database.delete(TRACK_TABLE, selection, selectionArgs);
                break;

            case PROVIDE_TRACK_ID:
                String segment = uri.getPathSegments().get(1);

                count = database.delete(TRACK_TABLE, TRACK_ID
                        + " = "
                        + segment
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection
                                + ")" : ""), selectionArgs);
                break;

            default:
                throw new SQLException("Unsupported Uri " + uri);
        }

        Log.d(TAG, count + " lines removed");
        getContext().getContentResolver().notifyChange(uri, null);

        return count;
    }

    /* ======================================================= */
    /*
     * @see android.content.ContentProvider#getType(android.net.Uri)
     */
    /* ======================================================= */
    @Override
    public String getType(Uri uri)
    {
        return null;
    }

    /* ======================================================= */
    /*
     * @see android.content.ContentProvider#insert(android.net.Uri,
     * android.content.ContentValues)
     */
    /* ======================================================= */
    @Override
    public Uri insert(Uri uri, ContentValues values)
    {

        long trackid = database.insert(TRACK_TABLE, "track", values);

        if (trackid > 0)
        {
            Log.d(TAG, "1 track inserted");
            Uri newUri = ContentUris.withAppendedId(CONTENT_URI, trackid);
            getContext().getContentResolver().notifyChange(newUri, null);
            return newUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    /* ======================================================= */
    /*
     * @see android.content.ContentProvider#onCreate()
     */
    /* ======================================================= */
    @Override
    public boolean onCreate()
    {
        Context context = getContext();
        helper = new IsiHikingOpenHelper(context,
                IsiHikingOpenHelper.DATABASE_NAME, null,
                IsiHikingOpenHelper.DATABASE_VERSION);
        database = helper.getWritableDatabase();
        Log.d(TAG, "Connection established to " + database.getPath()
                + " database");
        Log.d(TAG, "Provider created");

        return !(database == null);
    }

    /* ======================================================= */
    /*
     * @see android.content.ContentProvider#query(android.net.Uri,
     * java.lang.String[], java.lang.String, java.lang.String[],
     * java.lang.String)
     */
    /* ======================================================= */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder)
    {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(TRACK_TABLE);

        if (uriMatcher.match(uri) == PROVIDE_TRACK_ID)
        {
            qb.appendWhere(TRACK_ID + "=" + uri.getPathSegments().get(1));
            Log.d(TAG, "Searching track #" + uri.getPathSegments().get(1));
        }

        String orderBy = (TextUtils.isEmpty(sortOrder)) ? TRACK_ID : sortOrder;

        Cursor c = qb.query(database, projection, selection, selectionArgs,
                null, null, orderBy);

        c.setNotificationUri(getContext().getContentResolver(), uri);

        Log.d(TAG, c.getCount() + " lines selected");
        return c;
    }

    /* ======================================================= */
    /*
     * @see android.content.ContentProvider#update(android.net.Uri,
     * android.content.ContentValues, java.lang.String, java.lang.String[])
     */
    /* ======================================================= */
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs)
    {
        return 0;
    }

    private static class IsiHikingOpenHelper extends SQLiteOpenHelper
    {
        /** Debug Tag */
        private static final String TAG              = "IsiHikingOpenHelper";

        /* ======================================================= */
        /* DATABASE */
        /* ======================================================= */
        /** Database Name */
        public static final String  DATABASE_NAME    = "isihiking.db";
        /** Database Version */
        private static final int    DATABASE_VERSION = 1;

        /** Manipulate Track Table */
        private static final String TRACK_CREATE     = "CREATE TABLE track ( track_id INTEGER PRIMARY KEY AUTOINCREMENT,  track_name TEXT, track_path TEXT, track_date INTEGER, track_freq_refresh INTEGER, track_dist_refresh INTEGER )";

        private static final String TRACK_DROP       = "DROP TABLE IF EXISTS track";

        public IsiHikingOpenHelper(Context context, String name,
                CursorFactory factory, int version)
        {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(TRACK_CREATE);
            Log.d(TAG, "Database Created : " + TRACK_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading from version " + oldVersion + " to "
                    + newVersion + ", wich will destroy all old data");
            db.execSQL(TRACK_DROP);
            Log.d(TAG, "Tables removed : " + TRACK_DROP);

            onCreate(db);
        }

    }

}